home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / src / net / readline-2.0mg.tar.gz / readline-2.0mg.tar / readline-2.0mg / history.c < prev    next >
C/C++ Source or Header  |  1994-08-03  |  52KB  |  2,172 lines

  1. /* History.c -- standalone history library */
  2.  
  3. /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
  4.  
  5.    This file contains the GNU History Library (the Library), a set of
  6.    routines for managing the text of previously typed lines.
  7.  
  8.    The Library is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 1, or (at your option)
  11.    any later version.
  12.  
  13.    The Library is distributed in the hope that it will be useful, but
  14.    WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.    General Public License for more details.
  17.  
  18.    The GNU General Public License is often shipped with GNU software, and
  19.    is generally kept in a file called COPYING or LICENSE.  If you do not
  20.    have a copy of the license, write to the Free Software Foundation,
  21.    675 Mass Ave, Cambridge, MA 02139, USA. */
  22.  
  23. /* The goal is to make the implementation transparent, so that you
  24.    don't have to know what data types are used, just what functions
  25.    you can call.  I think I have done that. */
  26. #define READLINE_LIBRARY
  27.  
  28. #if defined (HAVE_CONFIG_H)
  29. #  include "config.h"
  30. #endif
  31.  
  32. #include <stdio.h>
  33. #include <sys/types.h>
  34. #include <sys/file.h>
  35. #include <sys/stat.h>
  36. #include <fcntl.h>
  37. #if defined (HAVE_STDLIB_H)
  38. #  include <stdlib.h>
  39. #else
  40. #  include "ansi_stdlib.h"
  41. #endif /* HAVE_STDLIB_H */
  42. #if defined (HAVE_UNISTD_H)
  43. #  include <unistd.h>
  44. #endif
  45. #if defined (HAVE_STRING_H)
  46. #  include <string.h>
  47. #else
  48. #  include <strings.h>
  49. #endif /* !HAVE_STRING_H */
  50. #include <errno.h>
  51.  
  52. /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
  53. #if !defined (errno)
  54. extern int errno;
  55. #endif /* !errno */
  56.  
  57. #include "memalloc.h"
  58. #include "history.h"
  59.  
  60. #if defined (STATIC_MALLOC)
  61. static char *xmalloc (), *xrealloc ();
  62. #else
  63. extern char *xmalloc (), *xrealloc ();
  64. #endif /* STATIC_MALLOC */
  65.  
  66. #define STREQ(a, b)    (((a)[0] == (b)[0]) && (strcmp ((a), (b)) == 0))
  67. #define STREQN(a, b, n)    (((a)[0] == (b)[0]) && (strncmp ((a), (b), (n)) == 0))
  68.  
  69. #ifndef savestring
  70. #  ifndef strcpy
  71. extern char *strcpy ();
  72. #  endif
  73. #define savestring(x) strcpy (xmalloc (1 + strlen (x)), (x))
  74. #endif
  75.  
  76. #ifndef whitespace
  77. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  78. #endif
  79.  
  80. #ifndef digit_p
  81. #define digit_p(c)  ((c) >= '0' && (c) <= '9')
  82. #endif
  83.  
  84. #ifndef digit_value
  85. #define digit_value(c) ((c) - '0')
  86. #endif
  87.  
  88. #ifndef member
  89. #  ifndef strchr
  90. extern char *strchr ();
  91. #  endif
  92. #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
  93. #endif
  94.  
  95. /* Possible history errors passed to hist_error. */
  96. #define EVENT_NOT_FOUND 0
  97. #define BAD_WORD_SPEC    1
  98. #define SUBST_FAILED    2
  99. #define BAD_MODIFIER    3
  100.  
  101. static char error_pointer;
  102.  
  103. static char *subst_lhs;
  104. static char *subst_rhs;
  105. static int subst_lhs_len = 0;
  106. static int subst_rhs_len = 0;
  107.  
  108. static char *get_history_word_specifier ();
  109.  
  110. #if defined (SHELL)
  111. extern char *single_quote ();
  112. #endif
  113.  
  114. /* **************************************************************** */
  115. /*                                    */
  116. /*            History Functions                */
  117. /*                                    */
  118. /* **************************************************************** */
  119.  
  120. /* An array of HIST_ENTRY.  This is where we store the history. */
  121. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  122.  
  123. /* Non-zero means that we have enforced a limit on the amount of
  124.    history that we save. */
  125. static int history_stifled = 0;
  126.  
  127. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  128.    entries to remember. */
  129. int max_input_history;
  130.  
  131. /* The current location of the interactive history pointer.  Just makes
  132.    life easier for outside callers. */
  133. static int history_offset = 0;
  134.  
  135. /* The number of strings currently stored in the input_history list. */
  136. int history_length = 0;
  137.  
  138. /* The current number of slots allocated to the input_history. */
  139. static int history_size = 0;
  140.  
  141. /* The number of slots to increase the_history by. */
  142. #define DEFAULT_HISTORY_GROW_SIZE 50
  143.  
  144. /* The character that represents the start of a history expansion
  145.    request.  This is usually `!'. */
  146. char history_expansion_char = '!';
  147.  
  148. /* The character that invokes word substitution if found at the start of
  149.    a line.  This is usually `^'. */
  150. char history_subst_char = '^';
  151.  
  152. /* During tokenization, if this character is seen as the first character
  153.    of a word, then it, and all subsequent characters upto a newline are
  154.    ignored.  For a Bourne shell, this should be '#'.  Bash special cases
  155.    the interactive comment character to not be a comment delimiter. */
  156. char history_comment_char = '\0';
  157.  
  158. /* The list of characters which inhibit the expansion of text if found
  159.    immediately following history_expansion_char. */
  160. char *history_no_expand_chars = " \t\n\r=";
  161.  
  162. /* The logical `base' of the history array.  It defaults to 1. */
  163. int history_base = 1;
  164.  
  165. /* Return the current HISTORY_STATE of the history. */
  166. HISTORY_STATE *
  167. history_get_history_state ()
  168. {
  169.   HISTORY_STATE *state;
  170.  
  171.   state = (HISTORY_STATE *)xmalloc (sizeof (HISTORY_STATE));
  172.   state->entries = the_history;
  173.   state->offset = history_offset;
  174.   state->length = history_length;
  175.   state->size = history_size;
  176.   state->flags = 0;
  177.   if (history_stifled)
  178.     state->flags |= HS_STIFLED;
  179.  
  180.   return (state);
  181. }
  182.  
  183. /* Set the state of the current history array to STATE. */
  184. void
  185. history_set_history_state (state)
  186.      HISTORY_STATE *state;
  187. {
  188.   the_history = state->entries;
  189.   history_offset = state->offset;
  190.   history_length = state->length;
  191.   history_size = state->size;
  192.   if (state->flags & HS_STIFLED)
  193.     history_stifled = 1;
  194. }
  195.  
  196. /* Begin a session in which the history functions might be used.  This
  197.    initializes interactive variables. */
  198. void
  199. using_history ()
  200. {
  201.   history_offset = history_length;
  202. }
  203.  
  204. /* Return the number of bytes that the primary history entries are using.
  205.    This just adds up the lengths of the_history->lines. */
  206. int
  207. history_total_bytes ()
  208. {
  209.   register int i, result;
  210.  
  211.   result = 0;
  212.  
  213.   for (i = 0; the_history && the_history[i]; i++)
  214.     result += strlen (the_history[i]->line);
  215.  
  216.   return (result);
  217. }
  218.  
  219. /* Place STRING at the end of the history list.  The data field
  220.    is  set to NULL. */
  221. void
  222. add_history (string)
  223.      char *string;
  224. {
  225.   HIST_ENTRY *temp;
  226.  
  227.   if (history_stifled && (history_length == max_input_history))
  228.     {
  229.       register int i;
  230.  
  231.       /* If the history is stifled, and history_length is zero,
  232.      and it equals max_input_history, we don't save items. */
  233.       if (history_length == 0)
  234.     return;
  235.  
  236.       /* If there is something in the slot, then remove it. */
  237.       if (the_history[0])
  238.     {
  239.       free (the_history[0]->line);
  240.       free (the_history[0]);
  241.     }
  242.  
  243.       /* Copy the rest of the entries, moving down one slot. */
  244.       for (i = 0; i < history_length; i++)
  245.     the_history[i] = the_history[i + 1];
  246.  
  247.       history_base++;
  248.  
  249.     }
  250.   else
  251.     {
  252.       if (!history_size)
  253.     {
  254.       history_size = DEFAULT_HISTORY_GROW_SIZE;
  255.       the_history = (HIST_ENTRY **)xmalloc (history_size * sizeof (HIST_ENTRY *));
  256.       history_length = 1;
  257.  
  258.     }
  259.       else
  260.     {
  261.       if (history_length == (history_size - 1))
  262.         {
  263.           history_size += DEFAULT_HISTORY_GROW_SIZE;
  264.           the_history = (HIST_ENTRY **)
  265.         xrealloc (the_history, history_size * sizeof (HIST_ENTRY *));
  266.         }
  267.       history_length++;
  268.     }
  269.     }
  270.  
  271.   temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  272.   temp->line = savestring (string);
  273.   temp->data = (char *)NULL;
  274.  
  275.   the_history[history_length] = (HIST_ENTRY *)NULL;
  276.   the_history[history_length - 1] = temp;
  277. }
  278.  
  279. /* Make the history entry at WHICH have LINE and DATA.  This returns
  280.    the old entry so you can dispose of the data.  In the case of an
  281.    invalid WHICH, a NULL pointer is returned. */
  282. HIST_ENTRY *
  283. replace_history_entry (which, line, data)
  284.      int which;
  285.      char *line;
  286.      char *data;
  287. {
  288.   HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  289.   HIST_ENTRY *old_value;
  290.  
  291.   if (which >= history_length)
  292.     return ((HIST_ENTRY *)NULL);
  293.  
  294.   old_value = the_history[which];
  295.  
  296.   temp->line = savestring (line);
  297.   temp->data = data;
  298.   the_history[which] = temp;
  299.  
  300.   return (old_value);
  301. }
  302.  
  303. /* Returns the magic number which says what history element we are
  304.    looking at now.  In this implementation, it returns history_offset. */
  305. int
  306. where_history ()
  307. {
  308.   return (history_offset);
  309. }
  310.  
  311. /* Search the history for STRING, starting at history_offset.
  312.    If DIRECTION < 0, then the search is through previous entries, else
  313.    through subsequent.  If ANCHORED is non-zero, the string must
  314.    appear at the beginning of a history line, otherwise, the string
  315.    may appear anywhere in the line.  If the string is found, then
  316.    current_history () is the history entry, and the value of this
  317.    function is the offset in the line of that history entry that the
  318.    string was found in.  Otherwise, nothing is changed, and a -1 is
  319.    returned. */
  320.  
  321. #define ANCHORED_SEARCH 1
  322. #define NON_ANCHORED_SEARCH 0
  323.  
  324. static int
  325. history_search_internal (string, direction, anchored)
  326.      char *string;
  327.      int direction, anchored;
  328. {
  329.   register int i, reverse;
  330.   register char *line;
  331.   register int line_index;
  332.   int string_len;
  333.  
  334.   i = history_offset;
  335.   reverse = (direction < 0);
  336.  
  337.   /* Take care of trivial cases first. */
  338.  
  339.   if (!history_length || ((i == history_length) && !reverse))
  340.     return (-1);
  341.  
  342.   if (reverse && (i == history_length))
  343.     i--;
  344.  
  345. #define NEXT_LINE() do { if (reverse) i--; else i++; } while (0)
  346.  
  347.   string_len = strlen (string);
  348.   while (1)
  349.     {
  350.       /* Search each line in the history list for STRING. */
  351.  
  352.       /* At limit for direction? */
  353.       if ((reverse && i < 0) || (!reverse && i == history_length))
  354.     return (-1);
  355.  
  356.       line = the_history[i]->line;
  357.       line_index = strlen (line);
  358.  
  359.       /* If STRING is longer than line, no match. */
  360.       if (string_len > line_index)
  361.     {
  362.       NEXT_LINE ();
  363.       continue;
  364.     }
  365.  
  366.       /* Handle anchored searches first. */
  367.       if (anchored == ANCHORED_SEARCH)
  368.     {
  369.       if (STREQN (string, line, string_len))
  370.         {
  371.           history_offset = i;
  372.           return (0);
  373.         }
  374.  
  375.       NEXT_LINE ();
  376.       continue;
  377.     }
  378.  
  379.       /* Do substring search. */
  380.       if (reverse)
  381.     {
  382.       line_index -= string_len;
  383.  
  384.       while (line_index >= 0)
  385.         {
  386.           if (STREQN (string, line + line_index, string_len))
  387.         {
  388.           history_offset = i;
  389.           return (line_index);
  390.         }
  391.           line_index--;
  392.         }
  393.     }
  394.       else
  395.     {
  396.       register int limit = line_index - string_len + 1;
  397.       line_index = 0;
  398.  
  399.       while (line_index < limit)
  400.         {
  401.           if (STREQN (string, line + line_index, string_len))
  402.         {
  403.           history_offset = i;
  404.           return (line_index);
  405.         }
  406.           line_index++;
  407.         }
  408.     }
  409.       NEXT_LINE ();
  410.     }
  411. }
  412.  
  413. /* Do a non-anchored search for STRING through the history in DIRECTION. */
  414. int
  415. history_search (string, direction)
  416.      char *string;
  417.      int direction;
  418. {
  419.   return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
  420. }
  421.  
  422. /* Do an anchored search for string through the history in DIRECTION. */
  423. int
  424. history_search_prefix (string, direction)
  425.      char *string;
  426.      int direction;
  427. {
  428.   return (history_search_internal (string, direction, ANCHORED_SEARCH));
  429. }
  430.  
  431. /* Remove history element WHICH from the history.  The removed
  432.    element is returned to you so you can free the line, data,
  433.    and containing structure. */
  434. HIST_ENTRY *
  435. remove_history (which)
  436.      int which;
  437. {
  438.   HIST_ENTRY *return_value;
  439.  
  440.   if (which >= history_length || !history_length)
  441.     return_value = (HIST_ENTRY *)NULL;
  442.   else
  443.     {
  444.       register int i;
  445.       return_value = the_history[which];
  446.  
  447.       for (i = which; i < history_length; i++)
  448.     the_history[i] = the_history[i + 1];
  449.  
  450.       history_length--;
  451.     }
  452.  
  453.   return (return_value);
  454. }
  455.  
  456. /* Stifle the history list, remembering only MAX number of lines. */
  457. void
  458. stifle_history (max)
  459.      int max;
  460. {
  461.   if (max < 0)
  462.     max = 0;
  463.  
  464.   if (history_length > max)
  465.     {
  466.       register int i, j;
  467.  
  468.       /* This loses because we cannot free the data. */
  469.       for (i = 0; i < (history_length - max); i++)
  470.     {
  471.       free (the_history[i]->line);
  472.       free (the_history[i]);
  473.     }
  474.  
  475.       history_base = i;
  476.       for (j = 0, i = history_length - max; j < max; i++, j++)
  477.     the_history[j] = the_history[i];
  478.       the_history[j] = (HIST_ENTRY *)NULL;
  479.       history_length = j;
  480.     }
  481.  
  482.   history_stifled = 1;
  483.   max_input_history = max;
  484. }
  485.  
  486. /* Stop stifling the history.  This returns the previous amount the history
  487.  was stifled by.  The value is positive if the history was stifled, negative
  488.  if it wasn't. */
  489. int
  490. unstifle_history ()
  491. {
  492.   int result = max_input_history;
  493.  
  494.   if (history_stifled)
  495.     {
  496.       result = -result;
  497.       history_stifled = 0;
  498.     }
  499.  
  500.   return (result);
  501. }
  502.  
  503. int
  504. history_is_stifled ()
  505. {
  506.   return (history_stifled);
  507. }
  508.  
  509. /* Return the string that should be used in the place of this
  510.    filename.  This only matters when you don't specify the
  511.    filename to read_history (), or write_history (). */
  512. static char *
  513. history_filename (filename)
  514.      char *filename;
  515. {
  516.   char *return_val = filename ? savestring (filename) : (char *)NULL;
  517.  
  518.   if (!return_val)
  519.     {
  520.       char *home;
  521.       int home_len;
  522.  
  523.       home = getenv ("HOME");
  524.  
  525.       if (!home)
  526.     home = ".";
  527.  
  528.       home_len = strlen (home);
  529.       /* strlen(".history") == 8 */
  530.       return_val = xmalloc (2 + home_len + 8);
  531.  
  532.       strcpy (return_val, home);
  533.       return_val[home_len] = '/';
  534.       strcpy (return_val + home_len + 1, ".history");
  535.     }
  536.  
  537.   return (return_val);
  538. }
  539.  
  540. /* Add the contents of FILENAME to the history list, a line at a time.
  541.    If FILENAME is NULL, then read from ~/.history.  Returns 0 if
  542.    successful, or errno if not. */
  543. int
  544. read_history (filename)
  545.      char *filename;
  546. {
  547.   return (read_history_range (filename, 0, -1));
  548. }
  549.  
  550. /* Read a range of lines from FILENAME, adding them to the history list.
  551.    Start reading at the FROM'th line and end at the TO'th.  If FROM
  552.    is zero, start at the beginning.  If TO is less than FROM, read
  553.    until the end of the file.  If FILENAME is NULL, then read from
  554.    ~/.history.  Returns 0 if successful, or errno if not. */
  555. int
  556. read_history_range (filename, from, to)
  557.      char *filename;
  558.      int from, to;
  559. {
  560.   register int line_start, line_end;
  561.   char *input, *buffer = (char *)NULL;
  562.   int file, current_line;
  563.   struct stat finfo;
  564.  
  565.   input = history_filename (filename);
  566.   file = open (input, O_RDONLY, 0666);
  567.  
  568.   if ((file < 0) || (fstat (file, &finfo) == -1))
  569.     goto error_and_exit;
  570.  
  571.   buffer = xmalloc ((int)finfo.st_size + 1);
  572.  
  573.   if (read (file, buffer, finfo.st_size) != finfo.st_size)
  574.     {
  575.   error_and_exit:
  576.       if (file >= 0)
  577.     close (file);
  578.  
  579.       if (input)
  580.     free (input);
  581.  
  582.       if (buffer)
  583.     free (buffer);
  584.  
  585.       return (errno);
  586.     }
  587.  
  588.   close (file);
  589.  
  590.   /* Set TO to larger than end of file if negative. */
  591.   if (to < 0)
  592.     to = finfo.st_size;
  593.  
  594.   /* Start at beginning of file, work to end. */
  595.   line_start = line_end = current_line = 0;
  596.  
  597.   /* Skip lines until we are at FROM. */
  598.   while (line_start < finfo.st_size && current_line < from)
  599.     {
  600.       for (line_end = line_start; line_end < finfo.st_size; line_end++)
  601.     if (buffer[line_end] == '\n')
  602.       {
  603.         current_line++;
  604.         line_start = line_end + 1;
  605.         if (current_line == from)
  606.           break;
  607.       }
  608.     }
  609.  
  610.   /* If there are lines left to gobble, then gobble them now. */
  611.   for (line_end = line_start; line_end < finfo.st_size; line_end++)
  612.     if (buffer[line_end] == '\n')
  613.       {
  614.     buffer[line_end] = '\0';
  615.  
  616.     if (buffer[line_start])
  617.       add_history (buffer + line_start);
  618.  
  619.     current_line++;
  620.  
  621.     if (current_line >= to)
  622.       break;
  623.  
  624.     line_start = line_end + 1;
  625.       }
  626.  
  627.   if (input)
  628.     free (input);
  629.  
  630.   if (buffer)
  631.     free (buffer);
  632.  
  633.   return (0);
  634. }
  635.  
  636. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  637.    If FNAME is NULL, then use ~/.history. */
  638. int
  639. history_truncate_file (fname, lines)
  640.      char *fname;
  641.      register int lines;
  642. {
  643.   register int i;
  644.   int file, chars_read;
  645.   char *buffer = (char *)NULL, *filename;
  646.   struct stat finfo;
  647.  
  648.   filename = history_filename (fname);
  649.   file = open (filename, O_RDONLY, 0666);
  650.  
  651.   if (file == -1 || fstat (file, &finfo) == -1)
  652.     goto truncate_exit;
  653.  
  654.   buffer = xmalloc ((int)finfo.st_size + 1);
  655.   chars_read = read (file, buffer, finfo.st_size);
  656.   close (file);
  657.  
  658.   if (chars_read <= 0)
  659.     goto truncate_exit;
  660.  
  661.   /* Count backwards from the end of buffer until we have passed
  662.      LINES lines. */
  663.   for (i = chars_read - 1; lines && i; i--)
  664.     {
  665.       if (buffer[i] == '\n')
  666.     lines--;
  667.     }
  668.  
  669.   /* If this is the first line, then the file contains exactly the
  670.      number of lines we want to truncate to, so we don't need to do
  671.      anything.  It's the first line if we don't find a newline between
  672.      the current value of i and 0.  Otherwise, write from the start of
  673.      this line until the end of the buffer. */
  674.   for ( ; i; i--)
  675.     if (buffer[i] == '\n')
  676.       {
  677.     i++;
  678.     break;
  679.       }
  680.  
  681.   /* Write only if there are more lines in the file than we want to
  682.      truncate to. */
  683.   if (i && ((file = open (filename, O_WRONLY|O_TRUNC, 0666)) != -1))
  684.     {
  685.       write (file, buffer + i, finfo.st_size - i);
  686.       close (file);
  687.     }
  688.  
  689.  truncate_exit:
  690.   if (buffer)
  691.     free (buffer);
  692.  
  693.   free (filename);
  694.   return 0;
  695. }
  696.  
  697. #define HISTORY_APPEND 0
  698. #define HISTORY_OVERWRITE 1
  699.  
  700. /* Workhorse function for writing history.  Writes NELEMENT entries
  701.    from the history list to FILENAME.  OVERWRITE is non-zero if you
  702.    wish to replace FILENAME with the entries. */
  703. static int
  704. history_do_write (filename, nelements, overwrite)
  705.      char *filename;
  706.      int nelements, overwrite;
  707. {
  708.   register int i;
  709.   char *output = history_filename (filename);
  710.   int file, mode;
  711.  
  712.   mode = overwrite ? O_WRONLY | O_CREAT | O_TRUNC : O_WRONLY | O_APPEND;
  713.  
  714.   if ((file = open (output, mode, 0666)) == -1)
  715.     {
  716.       if (output)
  717.     free (output);
  718.  
  719.       return (errno);
  720.     }
  721.  
  722.   if (nelements > history_length)
  723.     nelements = history_length;
  724.  
  725.   /* Build a buffer of all the lines to write, and write them in one syscall.
  726.      Suggested by Peter Ho (peter@robosts.oxford.ac.uk). */
  727.   {
  728.     register int j = 0;
  729.     int buffer_size = 0;
  730.     char *buffer;
  731.  
  732.     /* Calculate the total number of bytes to write. */
  733.     for (i = history_length - nelements; i < history_length; i++)
  734.       buffer_size += 1 + strlen (the_history[i]->line);
  735.  
  736.     /* Allocate the buffer, and fill it. */
  737.     buffer = xmalloc (buffer_size);
  738.  
  739.     for (i = history_length - nelements; i < history_length; i++)
  740.       {
  741.     strcpy (buffer + j, the_history[i]->line);
  742.     j += strlen (the_history[i]->line);
  743.     buffer[j++] = '\n';
  744.       }
  745.  
  746.     write (file, buffer, buffer_size);
  747.     free (buffer);
  748.   }
  749.  
  750.   close (file);
  751.  
  752.   if (output)
  753.     free (output);
  754.  
  755.   return (0);
  756. }
  757.  
  758. /* Append NELEMENT entries to FILENAME.  The entries appended are from
  759.    the end of the list minus NELEMENTs up to the end of the list. */
  760. int
  761. append_history (nelements, filename)
  762.      int nelements;
  763.      char *filename;
  764. {
  765.   return (history_do_write (filename, nelements, HISTORY_APPEND));
  766. }
  767.  
  768. /* Overwrite FILENAME with the current history.  If FILENAME is NULL,
  769.    then write the history list to ~/.history.  Values returned
  770.    are as in read_history ().*/
  771. int
  772. write_history (filename)
  773.      char *filename;
  774. {
  775.   return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  776. }
  777.  
  778. /* Return the history entry at the current position, as determined by
  779.    history_offset.  If there is no entry there, return a NULL pointer. */
  780. HIST_ENTRY *
  781. current_history ()
  782. {
  783.   if ((history_offset == history_length) || !the_history)
  784.     return ((HIST_ENTRY *)NULL);
  785.   else
  786.     return (the_history[history_offset]);
  787. }
  788.  
  789. /* Back up history_offset to the previous history entry, and return
  790.    a pointer to that entry.  If there is no previous entry then return
  791.    a NULL pointer. */
  792. HIST_ENTRY *
  793. previous_history ()
  794. {
  795.   if (!history_offset)
  796.     return ((HIST_ENTRY *)NULL);
  797.   else
  798.     return (the_history[--history_offset]);
  799. }
  800.  
  801. /* Move history_offset forward to the next history entry, and return
  802.    a pointer to that entry.  If there is no next entry then return a
  803.    NULL pointer. */
  804. HIST_ENTRY *
  805. next_history ()
  806. {
  807.   if (history_offset == history_length)
  808.     return ((HIST_ENTRY *)NULL);
  809.   else
  810.     return (the_history[++history_offset]);
  811. }
  812.  
  813. /* Return the current history array.  The caller has to be carefull, since this
  814.    is the actual array of data, and could be bashed or made corrupt easily.
  815.    The array is terminated with a NULL pointer. */
  816. HIST_ENTRY **
  817. history_list ()
  818. {
  819.   return (the_history);
  820. }
  821.  
  822. /* Return the history entry which is logically at OFFSET in the history array.
  823.    OFFSET is relative to history_base. */
  824. HIST_ENTRY *
  825. history_get (offset)
  826.      int offset;
  827. {
  828.   int local_index = offset - history_base;
  829.  
  830.   if (local_index >= history_length ||
  831.       local_index < 0 ||
  832.       !the_history)
  833.     return ((HIST_ENTRY *)NULL);
  834.   return (the_history[local_index]);
  835. }
  836.  
  837. /* Search for STRING in the history list.  DIR is < 0 for searching
  838.    backwards.  POS is an absolute index into the history list at
  839.    which point to begin searching. */
  840. int
  841. history_search_pos (string, dir, pos)
  842.      char *string;
  843.      int dir, pos;
  844. {
  845.   int ret, old = where_history ();
  846.   history_set_pos (pos);
  847.   if (history_search (string, dir) == -1)
  848.     {
  849.       history_set_pos (old);
  850.       return (-1);
  851.     }
  852.   ret = where_history ();
  853.   history_set_pos (old);
  854.   return ret;
  855. }
  856.  
  857. /* Make the current history item be the one at POS, an absolute index.
  858.    Returns zero if POS is out of range, else non-zero. */
  859. int
  860. history_set_pos (pos)
  861.      int pos;
  862. {
  863.   if (pos > history_length || pos < 0 || !the_history)
  864.     return (0);
  865.   history_offset = pos;
  866.   return (1);
  867. }
  868.  
  869.  
  870. /* **************************************************************** */
  871. /*                                    */
  872. /*            History Expansion                */
  873. /*                                    */
  874. /* **************************************************************** */
  875.  
  876. /* Hairy history expansion on text, not tokens.  This is of general
  877.    use, and thus belongs in this library. */
  878.  
  879. /* The last string searched for in a !?string? search. */
  880. static char *search_string = (char *)NULL;
  881.  
  882. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  883.    point to after the event specifier.  Just a pointer to the history
  884.    line is returned; NULL is returned in the event of a bad specifier.
  885.    You pass STRING with *INDEX equal to the history_expansion_char that
  886.    begins this specification.
  887.    DELIMITING_QUOTE is a character that is allowed to end the string
  888.    specification for what to search for in addition to the normal
  889.    characters `:', ` ', `\t', `\n', and sometimes `?'.
  890.    So you might call this function like:
  891.    line = get_history_event ("!echo:p", &index, 0);  */
  892. char *
  893. get_history_event (string, caller_index, delimiting_quote)
  894.      char *string;
  895.      int *caller_index;
  896.      int delimiting_quote;
  897. {
  898.   register int i = *caller_index;
  899.   register char c;
  900.   HIST_ENTRY *entry;
  901.   int which, sign = 1;
  902.   int local_index, search_mode, substring_okay = 0;
  903.   char *temp;
  904.  
  905.   /* The event can be specified in a number of ways.
  906.  
  907.      !!   the previous command
  908.      !n   command line N
  909.      !-n  current command-line minus N
  910.      !str the most recent command starting with STR
  911.      !?str[?]
  912.       the most recent command containing STR
  913.  
  914.      All values N are determined via HISTORY_BASE. */
  915.  
  916.   if (string[i] != history_expansion_char)
  917.     return ((char *)NULL);
  918.  
  919.   /* Move on to the specification. */
  920.   i++;
  921.  
  922. #define RETURN_ENTRY(e, w) \
  923.     return ((e = history_get (w)) ? e->line : (char *)NULL)
  924.  
  925.   /* Handle !! case. */
  926.   if (string[i] == history_expansion_char)
  927.     {
  928.       i++;
  929.       which = history_base + (history_length - 1);
  930.       *caller_index = i;
  931.       RETURN_ENTRY (entry, which);
  932.     }
  933.  
  934.   /* Hack case of numeric line specification. */
  935.   if (string[i] == '-')
  936.     {
  937.       sign = -1;
  938.       i++;
  939.     }
  940.  
  941.   if (digit_p (string[i]))
  942.     {
  943.       /* Get the extent of the digits and compute the value. */
  944.       for (which = 0; digit_p (string[i]); i++)
  945.     which = (which * 10) + digit_value (string[i]);
  946.  
  947.       *caller_index = i;
  948.  
  949.       if (sign < 0)
  950.     which = (history_length + history_base) - which;
  951.  
  952.       RETURN_ENTRY (entry, which);
  953.     }
  954.  
  955.   /* This must be something to search for.  If the spec begins with
  956.      a '?', then the string may be anywhere on the line.  Otherwise,
  957.      the string must be found at the start of a line. */
  958.   if (string[i] == '?')
  959.     {
  960.       substring_okay++;
  961.       i++;
  962.     }
  963.  
  964.   /* Only a closing `?' or a newline delimit a substring search string. */
  965.   for (local_index = i; c = string[i]; i++)
  966.     if ((!substring_okay && (whitespace (c) || c == ':' ||
  967. #if defined (SHELL)
  968.       member (c, ";&()|<>") ||
  969. #endif /* SHELL */
  970.       string[i] == delimiting_quote)) ||
  971.     string[i] == '\n' ||
  972.     (substring_okay && string[i] == '?'))
  973.       break;
  974.  
  975.   temp = xmalloc (1 + (i - local_index));
  976.   strncpy (temp, &string[local_index], (i - local_index));
  977.   temp[i - local_index] = '\0';
  978.  
  979.   if (substring_okay && string[i] == '?')
  980.     i++;
  981.  
  982.   *caller_index = i;
  983.  
  984. #define FAIL_SEARCH() \
  985.   do { history_offset = history_length; free (temp) ; return (char *)NULL; } while (0)
  986.  
  987.   search_mode = substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH;
  988.   while (1)
  989.     {
  990.       local_index = history_search_internal (temp, -1, search_mode);
  991.  
  992.       if (local_index < 0)
  993.     FAIL_SEARCH ();
  994.  
  995.       if (local_index == 0 || substring_okay)
  996.     {
  997.       entry = current_history ();
  998.       history_offset = history_length;
  999.     
  1000.       /* If this was a substring search, then remember the
  1001.          string that we matched for word substitution. */
  1002.       if (substring_okay)
  1003.         {
  1004.           if (search_string)
  1005.         free (search_string);
  1006.           search_string = temp;
  1007.         }
  1008.       else
  1009.         free (temp);
  1010.       return (entry->line);
  1011.     }
  1012.  
  1013.       if (history_offset)
  1014.     history_offset--;
  1015.       else
  1016.     FAIL_SEARCH ();
  1017.     }
  1018. #undef FAIL_SEARCH
  1019. #undef RETURN_ENTRY
  1020. }
  1021. #if defined (SHELL)
  1022. /* Function for extracting single-quoted strings.  Used for inhibiting
  1023.    history expansion within single quotes. */
  1024.  
  1025. /* Extract the contents of STRING as if it is enclosed in single quotes.
  1026.    SINDEX, when passed in, is the offset of the character immediately
  1027.    following the opening single quote; on exit, SINDEX is left pointing
  1028.    to the closing single quote. */
  1029. static void
  1030. rl_string_extract_single_quoted (string, sindex)
  1031.      char *string;
  1032.      int *sindex;
  1033. {
  1034.   register int i = *sindex;
  1035.  
  1036.   while (string[i] && string[i] != '\'')
  1037.     i++;
  1038.  
  1039.   *sindex = i;
  1040. }
  1041.  
  1042. static char *
  1043. quote_breaks (s)
  1044.      char *s;
  1045. {
  1046.   register char *p, *r;
  1047.   char *ret;
  1048.   int len = 3;
  1049.  
  1050.   for (p = s; p && *p; p++, len++)
  1051.     {
  1052.       if (*p == '\'')
  1053.     len += 3;
  1054.       else if (whitespace (*p) || *p == '\n')
  1055.     len += 2;
  1056.     }
  1057.  
  1058.   r = ret = xmalloc (len);
  1059.   *r++ = '\'';
  1060.   for (p = s; p && *p; )
  1061.     {
  1062.       if (*p == '\'')
  1063.     {
  1064.       *r++ = '\'';
  1065.       *r++ = '\\';
  1066.       *r++ = '\'';
  1067.       *r++ = '\'';
  1068.       p++;
  1069.     }
  1070.       else if (whitespace (*p) || *p == '\n')
  1071.     {
  1072.       *r++ = '\'';
  1073.       *r++ = *p++;
  1074.       *r++ = '\'';
  1075.     }
  1076.       else
  1077.     *r++ = *p++;
  1078.     }
  1079.   *r++ = '\'';
  1080.   *r = '\0';
  1081.   return ret;
  1082. }
  1083. #endif /* SHELL */
  1084.  
  1085. static char *
  1086. hist_error(s, start, current, errtype)
  1087.       char *s;
  1088.       int start, current, errtype;
  1089. {
  1090.   char *temp, *emsg;
  1091.   int ll, elen;
  1092.  
  1093.   ll = current - start;
  1094.  
  1095.   switch (errtype)
  1096.     {
  1097.     case EVENT_NOT_FOUND:
  1098.       emsg = "event not found";
  1099.       elen = 15;
  1100.       break;
  1101.     case BAD_WORD_SPEC:
  1102.       emsg = "bad word specifier";
  1103.       elen = 18;
  1104.       break;
  1105.     case SUBST_FAILED:
  1106.       emsg = "substitution failed";
  1107.       elen = 19;
  1108.       break;
  1109.     case BAD_MODIFIER:
  1110.       emsg = "unrecognized history modifier";
  1111.       elen = 29;
  1112.       break;
  1113.     default:
  1114.       emsg = "unknown expansion error";
  1115.       elen = 23;
  1116.       break;
  1117.     }
  1118.  
  1119.   temp = xmalloc (ll + elen + 3);
  1120.   strncpy (temp, s + start, ll);
  1121.   temp[ll] = ':';
  1122.   temp[ll + 1] = ' ';
  1123.   strcpy (temp + ll + 2, emsg);
  1124.   return (temp);
  1125. }
  1126.  
  1127. /* Get a history substitution string from STR starting at *IPTR
  1128.    and return it.  The length is returned in LENPTR.
  1129.  
  1130.    A backslash can quote the delimiter.  If the string is the
  1131.    empty string, the previous pattern is used.  If there is
  1132.    no previous pattern for the lhs, the last history search
  1133.    string is used.
  1134.  
  1135.    If IS_RHS is 1, we ignore empty strings and set the pattern
  1136.    to "" anyway.  subst_lhs is not changed if the lhs is empty;
  1137.    subst_rhs is allowed to be set to the empty string. */
  1138.  
  1139. static char *
  1140. get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr)
  1141.      char *str;
  1142.      int *iptr, delimiter, is_rhs, *lenptr;
  1143. {
  1144.   register int si, i, j, k;
  1145.   char *s = (char *) NULL;
  1146.  
  1147.   i = *iptr;
  1148.  
  1149.   for (si = i; str[si] && str[si] != delimiter; si++)
  1150.     if (str[si] == '\\' && str[si + 1] == delimiter)
  1151.       si++;
  1152.  
  1153.   if (si > i || is_rhs)
  1154.     {
  1155.       s = xmalloc (si - i + 1);
  1156.       for (j = 0, k = i; k < si; j++, k++)
  1157.     {
  1158.       /* Remove a backslash quoting the search string delimiter. */
  1159.       if (str[k] == '\\' && str[k + 1] == delimiter)
  1160.         k++;
  1161.       s[j] = str[k];
  1162.     }
  1163.       s[j] = '\0';
  1164.       if (lenptr)
  1165.         *lenptr = j;
  1166.     }
  1167.  
  1168.   i = si;
  1169.   if (str[i])
  1170.     i++;
  1171.   *iptr = i;
  1172.  
  1173.   return s;
  1174. }
  1175.  
  1176. static void
  1177. postproc_subst_rhs ()
  1178. {
  1179.   char *new;
  1180.   int i, j, new_size;
  1181.  
  1182.   new = xmalloc (new_size = subst_rhs_len + subst_lhs_len);
  1183.   for (i = j = 0; i < subst_rhs_len; i++)
  1184.     {
  1185.       if (subst_rhs[i] == '&')
  1186.     {
  1187.       if (j + subst_lhs_len >= new_size)
  1188.         new = xrealloc (new, (new_size = new_size * 2 + subst_lhs_len));
  1189.       strcpy (new + j, subst_lhs);
  1190.       j += subst_lhs_len;
  1191.     }
  1192.       else
  1193.     {
  1194.       /* a single backslash protects the `&' from lhs interpolation */
  1195.       if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&')
  1196.         i++;
  1197.       if (j >= new_size)
  1198.         new = xrealloc (new, new_size *= 2);
  1199.       new[j++] = subst_rhs[i];
  1200.     }
  1201.     }
  1202.   new[j] = '\0';
  1203.   free (subst_rhs);
  1204.   subst_rhs = new;
  1205.   subst_rhs_len = j;
  1206. }
  1207.  
  1208. /* Expand the bulk of a history specifier starting at STRING[START].
  1209.    Returns 0 if everything is OK, -1 if an error occurred, and 1
  1210.    if the `p' modifier was supplied and the caller should just print
  1211.    the returned string.  Returns the new index into string in
  1212.    *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */
  1213. static int
  1214. history_expand_internal (string, start, end_index_ptr, ret_string, current_line)
  1215.      char *string;
  1216.      int start, *end_index_ptr;
  1217.      char **ret_string;
  1218.      char *current_line;    /* for !# */
  1219. {
  1220.   int i, n, starting_index;
  1221.   int substitute_globally, want_quotes, print_only;
  1222.   char *event, *temp, *result, *tstr, *t, c, *word_spec;
  1223.   int result_len;
  1224.  
  1225.   result = xmalloc (result_len = 128);
  1226.  
  1227.   i = start;
  1228.  
  1229.   /* If it is followed by something that starts a word specifier,
  1230.      then !! is implied as the event specifier. */
  1231.  
  1232.   if (member (string[i + 1], ":$*%^"))
  1233.     {
  1234.       char fake_s[3];
  1235.       int fake_i = 0;
  1236.       i++;
  1237.       fake_s[0] = fake_s[1] = history_expansion_char;
  1238.       fake_s[2] = '\0';
  1239.       event = get_history_event (fake_s, &fake_i, 0);
  1240.     }
  1241.   else if (string[i + 1] == '#')
  1242.     {
  1243.       i += 2;
  1244.       event = current_line;
  1245.     }
  1246.   else
  1247.     {
  1248.       int quoted_search_delimiter = 0;
  1249.  
  1250.       /* If the character before this `!' is a double or single
  1251.      quote, then this expansion takes place inside of the
  1252.      quoted string.  If we have to search for some text ("!foo"),
  1253.      allow the delimiter to end the search string. */
  1254.       if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  1255.     quoted_search_delimiter = string[i - 1];
  1256.       event = get_history_event (string, &i, quoted_search_delimiter);
  1257.     }
  1258.       
  1259.   if (!event)
  1260.     {
  1261.       *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND);
  1262.       free (result);
  1263.       return (-1);
  1264.     }
  1265.  
  1266.   /* If a word specifier is found, then do what that requires. */
  1267.   starting_index = i;
  1268.   word_spec = get_history_word_specifier (string, event, &i);
  1269.  
  1270.   /* There is no such thing as a `malformed word specifier'.  However,
  1271.      it is possible for a specifier that has no match.  In that case,
  1272.      we complain. */
  1273.   if (word_spec == (char *)&error_pointer)
  1274.     {
  1275.       *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC);
  1276.       free (result);
  1277.       return (-1);
  1278.     }
  1279.  
  1280.   /* If no word specifier, than the thing of interest was the event. */
  1281.   if (!word_spec)
  1282.     temp = savestring (event);
  1283.   else
  1284.     {
  1285.       temp = savestring (word_spec);
  1286.       free (word_spec);
  1287.     }
  1288.  
  1289.   /* Perhaps there are other modifiers involved.  Do what they say. */
  1290.   want_quotes = substitute_globally = print_only = 0;
  1291.   starting_index = i;
  1292.  
  1293.   while (string[i] == ':')
  1294.     {
  1295.       c = string[i + 1];
  1296.  
  1297.       if (c == 'g')
  1298.     {
  1299.       substitute_globally = 1;
  1300.       i++;
  1301.       c = string[i + 1];
  1302.     }
  1303.  
  1304.       switch (c)
  1305.     {
  1306.     default:
  1307.       *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER);
  1308.       free (result);
  1309.       free (temp);
  1310.       return -1;
  1311.  
  1312. #if defined (SHELL)
  1313.     case 'q':
  1314.       want_quotes = 'q';
  1315.       break;
  1316.  
  1317.     case 'x':
  1318.       want_quotes = 'x';
  1319.       break;
  1320. #endif /* SHELL */
  1321.  
  1322.       /* :p means make this the last executed line.  So we
  1323.          return an error state after adding this line to the
  1324.          history. */
  1325.     case 'p':
  1326.       print_only++;
  1327.       break;
  1328.  
  1329.       /* :t discards all but the last part of the pathname. */
  1330.     case 't':
  1331.       tstr = strrchr (temp, '/');
  1332.       if (tstr)
  1333.         {
  1334.           tstr++;
  1335.           t = savestring (tstr);
  1336.           free (temp);
  1337.           temp = t;
  1338.         }
  1339.       break;
  1340.  
  1341.       /* :h discards the last part of a pathname. */
  1342.     case 'h':
  1343.       tstr = strrchr (temp, '/');
  1344.       if (tstr)
  1345.         *tstr = '\0';
  1346.       break;
  1347.  
  1348.       /* :r discards the suffix. */
  1349.     case 'r':
  1350.       tstr = strrchr (temp, '.');
  1351.       if (tstr)
  1352.         *tstr = '\0';
  1353.       break;
  1354.  
  1355.       /* :e discards everything but the suffix. */
  1356.     case 'e':
  1357.       tstr = strrchr (temp, '.');
  1358.       if (tstr)
  1359.         {
  1360.           t = savestring (tstr);
  1361.           free (temp);
  1362.           temp = t;
  1363.         }
  1364.       break;
  1365.  
  1366.     /* :s/this/that substitutes `that' for the first
  1367.        occurrence of `this'.  :gs/this/that substitutes `that'
  1368.        for each occurrence of `this'.  :& repeats the last
  1369.        substitution.  :g& repeats the last substitution
  1370.        globally. */
  1371.  
  1372.     case '&':
  1373.     case 's':
  1374.       {
  1375.         char *new_event, *t;
  1376.         int delimiter, failed, si, l_temp;
  1377.  
  1378.         if (c == 's')
  1379.           {
  1380.         if (i + 2 < (int)strlen (string))
  1381.           delimiter = string[i + 2];
  1382.         else
  1383.           break;    /* no search delimiter */
  1384.  
  1385.         i += 3;
  1386.  
  1387.         t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len);
  1388.         /* An empty substitution lhs with no previous substitution
  1389.            uses the last search string as the lhs. */
  1390.         if (t)
  1391.           {
  1392.             if (subst_lhs)
  1393.               free (subst_lhs);
  1394.             subst_lhs = t;
  1395.           }
  1396.         else if (!subst_lhs)
  1397.           {
  1398.             if (search_string && *search_string)
  1399.               {
  1400.             subst_lhs = savestring (search_string);
  1401.             subst_lhs_len = strlen (subst_lhs);
  1402.               }
  1403.             else
  1404.               {
  1405.                 subst_lhs = (char *) NULL;
  1406.                 subst_lhs_len = 0;
  1407.               }
  1408.           }
  1409.  
  1410.         /* If there is no lhs, the substitution can't succeed. */
  1411.         if (subst_lhs_len == 0)
  1412.           {
  1413.             *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1414.             free (result);
  1415.             free (temp);
  1416.             return -1;
  1417.           }
  1418.  
  1419.         if (subst_rhs)
  1420.           free (subst_rhs);
  1421.         subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len);
  1422.  
  1423.         /* If `&' appears in the rhs, it's supposed to be replaced
  1424.            with the lhs. */
  1425.         if (member ('&', subst_rhs))
  1426.           postproc_subst_rhs ();
  1427.           }
  1428.         else
  1429.           i += 2;
  1430.  
  1431.         l_temp = strlen (temp);
  1432.         /* Ignore impossible cases. */
  1433.         if (subst_lhs_len > l_temp)
  1434.           {
  1435.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1436.         free (result);
  1437.         free (temp);
  1438.         return (-1);
  1439.           }
  1440.  
  1441.         /* Find the first occurrence of THIS in TEMP. */
  1442.         si = 0;
  1443.         for (failed = 1; (si + subst_lhs_len) <= l_temp; si++)
  1444.           if (STREQN (temp+si, subst_lhs, subst_lhs_len))
  1445.         {
  1446.           int len = subst_rhs_len - subst_lhs_len + l_temp;
  1447.           new_event = xmalloc (1 + len);
  1448.           strncpy (new_event, temp, si);
  1449.           strncpy (new_event + si, subst_rhs, subst_rhs_len);
  1450.           strncpy (new_event + si + subst_rhs_len,
  1451.                temp + si + subst_lhs_len,
  1452.                l_temp - (si + subst_lhs_len));
  1453.           new_event[len] = '\0';
  1454.           free (temp);
  1455.           temp = new_event;
  1456.  
  1457.           failed = 0;
  1458.  
  1459.           if (substitute_globally)
  1460.             {
  1461.               si += subst_rhs_len;
  1462.               l_temp = strlen (temp);
  1463.               substitute_globally++;
  1464.               continue;
  1465.             }
  1466.           else
  1467.             break;
  1468.         }
  1469.  
  1470.         if (substitute_globally > 1)
  1471.           {
  1472.         substitute_globally = 0;
  1473.         continue;    /* don't want to increment i */
  1474.           }
  1475.  
  1476.         if (failed == 0)
  1477.           continue;        /* don't want to increment i */
  1478.  
  1479.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1480.         free (result);
  1481.         free (temp);
  1482.         return (-1);
  1483.       }
  1484.     }
  1485.       i += 2;
  1486.     }
  1487.   /* Done with modfiers. */
  1488.   /* Believe it or not, we have to back the pointer up by one. */
  1489.   --i;
  1490.  
  1491. #if defined (SHELL)
  1492.   if (want_quotes)
  1493.     {
  1494.       char *x;
  1495.  
  1496.       if (want_quotes == 'q')
  1497.     x = single_quote (temp);
  1498.       else if (want_quotes == 'x')
  1499.     x = quote_breaks (temp);
  1500.       else
  1501.     x = savestring (temp);
  1502.  
  1503.       free (temp);
  1504.       temp = x;
  1505.     }
  1506. #endif /* SHELL */
  1507.  
  1508.   n = strlen (temp);
  1509.   if (n > result_len)
  1510.     result = xrealloc (result, n + 2);
  1511.   strcpy (result, temp);
  1512.   free (temp);
  1513.  
  1514.   *end_index_ptr = i;
  1515.   *ret_string = result;
  1516.   return (print_only);
  1517. }
  1518.  
  1519. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  1520.    to a string.  Returns:
  1521.  
  1522.   -1) If there was an error in expansion.
  1523.    0) If no expansions took place (or, if the only change in
  1524.       the text was the de-slashifying of the history expansion
  1525.       character)
  1526.    1) If expansions did take place
  1527.    2) If the `p' modifier was given and the caller should print the result
  1528.  
  1529.   If an error ocurred in expansion, then OUTPUT contains a descriptive
  1530.   error message. */
  1531.  
  1532. #define ADD_STRING(s) \
  1533.     do \
  1534.       { \
  1535.         int sl = strlen (s); \
  1536.         j += sl; \
  1537.         if (j >= result_len) \
  1538.           { \
  1539.             while (j >= result_len) \
  1540.               result_len += 128; \
  1541.             result = xrealloc (result, result_len); \
  1542.           } \
  1543.         strcpy (result + j - sl, s); \
  1544.       } \
  1545.     while (0)
  1546.  
  1547. #define ADD_CHAR(c) \
  1548.     do \
  1549.       { \
  1550.         if (j >= result_len - 1) \
  1551.           result = xrealloc (result, result_len += 64); \
  1552.         result[j++] = c; \
  1553.         result[j] = '\0'; \
  1554.       } \
  1555.     while (0)
  1556.  
  1557. int
  1558. history_expand (hstring, output)
  1559.      char *hstring;
  1560.      char **output;
  1561. {
  1562.   register int j;
  1563.   int i, r, l, passc, cc, modified, eindex, only_printing;
  1564.   char *string;
  1565.  
  1566.   /* The output string, and its length. */
  1567.   int result_len;
  1568.   char *result;
  1569.  
  1570.   /* Used when adding the string. */
  1571.   char *temp;
  1572.  
  1573.   /* Setting the history expansion character to 0 inhibits all
  1574.      history expansion. */
  1575.   if (history_expansion_char == 0)
  1576.     {
  1577.       *output = savestring (hstring);
  1578.       return (0);
  1579.     }
  1580.     
  1581.   /* Prepare the buffer for printing error messages. */
  1582.   result = xmalloc (result_len = 256);
  1583.   result[0] = '\0';
  1584.  
  1585.   only_printing = modified = 0;
  1586.   l = strlen (hstring);
  1587.  
  1588.   /* Grovel the string.  Only backslash can quote the history escape
  1589.      character.  We also handle arg specifiers. */
  1590.  
  1591.   /* Before we grovel forever, see if the history_expansion_char appears
  1592.      anywhere within the text. */
  1593.  
  1594.   /* The quick substitution character is a history expansion all right.  That
  1595.      is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  1596.      that is the substitution that we do. */
  1597.   if (hstring[0] == history_subst_char)
  1598.     {
  1599.       string = xmalloc (l + 5);
  1600.  
  1601.       string[0] = string[1] = history_expansion_char;
  1602.       string[2] = ':';
  1603.       string[3] = 's';
  1604.       strcpy (string + 4, hstring);
  1605.       l += 4;
  1606.     }
  1607.   else
  1608.     {
  1609.       string = hstring;
  1610.       /* If not quick substitution, still maybe have to do expansion. */
  1611.  
  1612.       /* `!' followed by one of the characters in history_no_expand_chars
  1613.      is NOT an expansion. */
  1614.       for (i = 0; string[i]; i++)
  1615.     {
  1616.       cc = string[i + 1];
  1617.           if (string[i] == history_expansion_char)
  1618.         {
  1619.           if (!cc || member (cc, history_no_expand_chars))
  1620.         continue;
  1621. #if defined (SHELL)
  1622.           /* The shell uses ! as a pattern negation character
  1623.              in globbing [...] expressions, so let those pass
  1624.              without expansion. */
  1625.           else if (i > 0 && (string[i - 1] == '[') &&
  1626.                member (']', string + i + 1))
  1627.         continue;
  1628. #endif /* SHELL */
  1629.           else
  1630.         break;
  1631.         }
  1632. #if defined (SHELL)
  1633.       else if (string[i] == '\'')
  1634.         {
  1635.           /* If this is bash, single quotes inhibit history expansion. */
  1636.           i++;
  1637.           rl_string_extract_single_quoted (string, &i);
  1638.         }
  1639.       else if (string[i] == '\\')
  1640.         {
  1641.           /* If this is bash, allow backslashes to quote single
  1642.          quotes and
  1643.          the history expansion character. */
  1644.           if (cc == '\'' || cc == history_expansion_char)
  1645.         i++;
  1646.         }
  1647. #endif /* SHELL */
  1648.     }
  1649.       
  1650.       if (string[i] != history_expansion_char)
  1651.     {
  1652.       free (result);
  1653.       *output = savestring (string);
  1654.       return (0);
  1655.     }
  1656.     }
  1657.  
  1658.   /* Extract and perform the substitution. */
  1659.   for (passc = i = j = 0; i < l; i++)
  1660.     {
  1661.       int tchar = string[i];
  1662.  
  1663.       if (passc)
  1664.     {
  1665.       passc = 0;
  1666.       ADD_CHAR (tchar);
  1667.       continue;
  1668.     }
  1669.  
  1670.       if (tchar == history_expansion_char)
  1671.     tchar = -3;
  1672.  
  1673.       switch (tchar)
  1674.     {
  1675.     default:
  1676.       ADD_CHAR (string[i]);
  1677.       break;
  1678.  
  1679.     case '\\':
  1680.       passc++;
  1681.       ADD_CHAR (tchar);
  1682.       break;
  1683.  
  1684. #if defined (SHELL)
  1685.     case '\'':
  1686.       {
  1687.         /* If this is bash, single quotes inhibit history expansion. */
  1688.         int quote, slen;
  1689.  
  1690.         quote = i++;
  1691.         rl_string_extract_single_quoted (string, &i);
  1692.  
  1693.         slen = i - quote + 2;
  1694.         temp = xmalloc (slen);
  1695.         strncpy (temp, string + quote, slen);
  1696.         temp[slen - 1] = '\0';
  1697.         ADD_STRING (temp);
  1698.         free (temp);
  1699.         break;
  1700.       }
  1701. #endif /* SHELL */
  1702.  
  1703.     case -3:        /* history_expansion_char */
  1704.       cc = string[i + 1];
  1705.  
  1706.       /* If the history_expansion_char is followed by one of the
  1707.          characters in history_no_expand_chars, then it is not a
  1708.          candidate for expansion of any kind. */
  1709.       if (member (cc, history_no_expand_chars))
  1710.         {
  1711.           ADD_CHAR (string[i]);
  1712.           break;
  1713.         }
  1714.  
  1715. #if defined (NO_BANG_HASH_MODIFIERS)
  1716.       /* There is something that is listed as a `word specifier' in csh
  1717.          documentation which means `the expanded text to this point'.
  1718.          That is not a word specifier, it is an event specifier.  If we
  1719.          don't want to allow modifiers with `!#', just stick the current
  1720.          output line in again. */
  1721.       if (cc == '#')
  1722.         {
  1723.           if (result)
  1724.         {
  1725.           temp = xmalloc (1 + strlen (result));
  1726.           strcpy (temp, result);
  1727.           ADD_STRING (temp);
  1728.           free (temp);
  1729.         }
  1730.           i++;
  1731.           break;
  1732.         }
  1733. #endif
  1734.  
  1735.       r = history_expand_internal (string, i, &eindex, &temp, result);
  1736.       if (r < 0)
  1737.         {
  1738.           *output = temp;
  1739.           free (result);
  1740.           if (string != hstring)
  1741.         free (string);
  1742.           return -1;
  1743.         }
  1744.       else
  1745.         {
  1746.           if (temp)
  1747.         {
  1748.           modified++;
  1749.           if (*temp)
  1750.             ADD_STRING (temp);
  1751.           free (temp);
  1752.         }
  1753.           only_printing = r == 1;
  1754.           i = eindex;
  1755.         }
  1756.       break;
  1757.     }
  1758.     }
  1759.  
  1760.   *output = result;
  1761.   if (string != hstring)
  1762.     free (string);
  1763.  
  1764.   if (only_printing)
  1765.     {
  1766.       add_history (result);
  1767.       return (2);
  1768.     }
  1769.  
  1770.   return (modified != 0);
  1771. }
  1772.  
  1773. /* Return a consed string which is the word specified in SPEC, and found
  1774.    in FROM.  NULL is returned if there is no spec.  The address of
  1775.    ERROR_POINTER is returned if the word specified cannot be found.
  1776.    CALLER_INDEX is the offset in SPEC to start looking; it is updated
  1777.    to point to just after the last character parsed. */
  1778. static char *
  1779. get_history_word_specifier (spec, from, caller_index)
  1780.      char *spec, *from;
  1781.      int *caller_index;
  1782. {
  1783.   register int i = *caller_index;
  1784.   int first, last;
  1785.   int expecting_word_spec = 0;
  1786.   char *result;
  1787.  
  1788.   /* The range of words to return doesn't exist yet. */
  1789.   first = last = 0;
  1790.   result = (char *)NULL;
  1791.  
  1792.   /* If we found a colon, then this *must* be a word specification.  If
  1793.      it isn't, then it is an error. */
  1794.   if (spec[i] == ':')
  1795.     {
  1796.       i++;
  1797.       expecting_word_spec++;
  1798.     }
  1799.  
  1800.   /* Handle special cases first. */
  1801.  
  1802.   /* `%' is the word last searched for. */
  1803.   if (spec[i] == '%')
  1804.     {
  1805.       *caller_index = i + 1;
  1806.       return (search_string ? savestring (search_string) : savestring (""));
  1807.     }
  1808.  
  1809.   /* `*' matches all of the arguments, but not the command. */
  1810.   if (spec[i] == '*')
  1811.     {
  1812.       *caller_index = i + 1;
  1813.       result = history_arg_extract (1, '$', from);
  1814.       return (result ? result : savestring (""));
  1815.     }
  1816.  
  1817.   /* `$' is last arg. */
  1818.   if (spec[i] == '$')
  1819.     {
  1820.       *caller_index = i + 1;
  1821.       return (history_arg_extract ('$', '$', from));
  1822.     }
  1823.  
  1824.   /* Try to get FIRST and LAST figured out. */
  1825.  
  1826.   if (spec[i] == '-')
  1827.     first = 0;
  1828.   else if (spec[i] == '^')
  1829.     first = 1;
  1830.   else if (digit_p (spec[i]) && expecting_word_spec)
  1831.     {
  1832.       for (first = 0; digit_p (spec[i]); i++)
  1833.     first = (first * 10) + digit_value (spec[i]);
  1834.     }
  1835.   else
  1836.     return ((char *)NULL);    /* no valid `first' for word specifier */
  1837.  
  1838.   if (spec[i] == '^' || spec[i] == '*')
  1839.     {
  1840.       last = (spec[i] == '^') ? 1 : '$';    /* x* abbreviates x-$ */
  1841.       i++;
  1842.     }
  1843.   else if (spec[i] != '-')
  1844.     last = first;
  1845.   else
  1846.     {
  1847.       i++;
  1848.  
  1849.       if (digit_p (spec[i]))
  1850.     {
  1851.       for (last = 0; digit_p (spec[i]); i++)
  1852.         last = (last * 10) + digit_value (spec[i]);
  1853.     }
  1854.       else if (spec[i] == '$')
  1855.     {
  1856.       i++;
  1857.       last = '$';
  1858.     }
  1859.       else if (!spec[i] || spec[i] == ':')  /* could be modifier separator */
  1860.     last = -1;        /* x- abbreviates x-$ omitting word `$' */
  1861.     }
  1862.  
  1863.   *caller_index = i;
  1864.  
  1865.   if (last >= first || last == '$' || last < 0)
  1866.     result = history_arg_extract (first, last, from);
  1867.  
  1868.   return (result ? result : (char *)&error_pointer);
  1869. }
  1870.  
  1871. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1872.    The args are taken from STRING.  If either FIRST or LAST is < 0,
  1873.    then make that arg count from the right (subtract from the number of
  1874.    tokens, so that FIRST = -1 means the next to last token on the line).
  1875.    If LAST is `$' the last arg from STRING is used. */
  1876. char *
  1877. history_arg_extract (first, last, string)
  1878.      int first, last;
  1879.      char *string;
  1880. {
  1881.   register int i, len;
  1882.   char *result = (char *)NULL;
  1883.   int size = 0, offset = 0;
  1884.   char **list;
  1885.  
  1886.   /* XXX - think about making history_tokenize return a struct array,
  1887.      each struct in array being a string and a length to avoid the
  1888.      calls to strlen below. */
  1889.   if ((list = history_tokenize (string)) == NULL)
  1890.     return ((char *)NULL);
  1891.  
  1892.   for (len = 0; list[len]; len++)
  1893.     ;
  1894.  
  1895.   if (last < 0)
  1896.     last = len + last - 1;
  1897.  
  1898.   if (first < 0)
  1899.     first = len + first - 1;
  1900.  
  1901.   if (last == '$')
  1902.     last = len - 1;
  1903.  
  1904.   if (first == '$')
  1905.     first = len - 1;
  1906.  
  1907.   last++;
  1908.  
  1909.   if (first > len || last > len || first < 0 || last < 0)
  1910.     result = ((char *)NULL);
  1911.   else
  1912.     {
  1913.       for (size = 0, i = first; i < last; i++)
  1914.     size += strlen (list[i]) + 1;
  1915.       result = xmalloc (size + 1);
  1916.  
  1917.       for (i = first; i < last; i++)
  1918.     {
  1919.       strcpy (result + offset, list[i]);
  1920.       offset += strlen (list[i]);
  1921.       if (i + 1 < last)
  1922.         {
  1923.                 result[offset++] = ' ';
  1924.           result[offset] = 0;
  1925.         }
  1926.     }
  1927.     }
  1928.  
  1929.   for (i = 0; i < len; i++)
  1930.     free (list[i]);
  1931.   free (list);
  1932.  
  1933.   return (result);
  1934. }
  1935.  
  1936. #define slashify_in_quotes "\\`\"$"
  1937.  
  1938. /* Return an array of tokens, much as the shell might.  The tokens are
  1939.    parsed out of STRING. */
  1940. char **
  1941. history_tokenize (string)
  1942.      char *string;
  1943. {
  1944.   char **result = (char **)NULL;
  1945.   register int i, start, result_index, size;
  1946.   int len;
  1947.  
  1948.   i = result_index = size = 0;
  1949.  
  1950.   /* Get a token, and stuff it into RESULT.  The tokens are split
  1951.      exactly where the shell would split them. */
  1952.   while (string[i])
  1953.     {
  1954.       int delimiter = 0;
  1955.  
  1956.       /* Skip leading whitespace. */
  1957.       for (; string[i] && whitespace (string[i]); i++)
  1958.     ;
  1959.       if (!string[i] || string[i] == history_comment_char)
  1960.     return (result);
  1961.  
  1962.       start = i;
  1963.       
  1964.       if (member (string[i], "()\n"))
  1965.     {
  1966.       i++;
  1967.       goto got_token;
  1968.     }
  1969.  
  1970.       if (member (string[i], "<>;&|$"))
  1971.     {
  1972.       int peek = string[i + 1];
  1973.  
  1974.       if (peek == string[i] && peek != '$')
  1975.         {
  1976.           if (peek == '<' && string[i + 2] == '-')
  1977.         i++;
  1978.           i += 2;
  1979.           goto got_token;
  1980.         }
  1981.       else
  1982.         {
  1983.           if ((peek == '&' && (string[i] == '>' || string[i] == '<')) ||
  1984.           ((peek == '>') && (string[i] == '&')) ||
  1985.           ((peek == '(') && (string[i] == '$')))
  1986.         {
  1987.           i += 2;
  1988.           goto got_token;
  1989.         }
  1990.         }
  1991.       if (string[i] != '$')
  1992.         {
  1993.           i++;
  1994.           goto got_token;
  1995.         }
  1996.     }
  1997.  
  1998.       /* Get word from string + i; */
  1999.  
  2000.       if (member (string[i], "\"'`"))
  2001.     delimiter = string[i++];
  2002.  
  2003.       for (; string[i]; i++)
  2004.     {
  2005.       if (string[i] == '\\' && string[i + 1] == '\n')
  2006.         {
  2007.           i++;
  2008.           continue;
  2009.         }
  2010.  
  2011.       if (string[i] == '\\' && delimiter != '\'' &&
  2012.           (delimiter != '"' || member (string[i], slashify_in_quotes)))
  2013.         {
  2014.           i++;
  2015.           continue;
  2016.         }
  2017.  
  2018.       if (delimiter && string[i] == delimiter)
  2019.         {
  2020.           delimiter = 0;
  2021.           continue;
  2022.         }
  2023.  
  2024.       if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  2025.         break;
  2026.  
  2027.       if (!delimiter && member (string[i], "\"'`"))
  2028.         delimiter = string[i];
  2029.     }
  2030.     got_token:
  2031.  
  2032.       len = i - start;
  2033.       if (result_index + 2 >= size)
  2034.     result = (char **)xrealloc (result, ((size += 10) * sizeof (char *)));
  2035.       result[result_index] = xmalloc (1 + len);
  2036.       strncpy (result[result_index], string + start, len);
  2037.       result[result_index][len] = '\0';
  2038.       result[++result_index] = (char *)NULL;
  2039.     }
  2040.  
  2041.   return (result);
  2042. }
  2043.  
  2044. #if defined (STATIC_MALLOC)
  2045.  
  2046. /* **************************************************************** */
  2047. /*                                    */
  2048. /*            xmalloc and xrealloc ()                     */
  2049. /*                                    */
  2050. /* **************************************************************** */
  2051.  
  2052. static void memory_error_and_abort ();
  2053.  
  2054. static char *
  2055. xmalloc (bytes)
  2056.      int bytes;
  2057. {
  2058.   char *temp = (char *)malloc (bytes);
  2059.  
  2060.   if (!temp)
  2061.     memory_error_and_abort ();
  2062.   return (temp);
  2063. }
  2064.  
  2065. static char *
  2066. xrealloc (pointer, bytes)
  2067.      char *pointer;
  2068.      int bytes;
  2069. {
  2070.   char *temp;
  2071.  
  2072.   if (!pointer)
  2073.     temp = (char *)xmalloc (bytes);
  2074.   else
  2075.     temp = (char *)realloc (pointer, bytes);
  2076.  
  2077.   if (!temp)
  2078.     memory_error_and_abort ();
  2079.  
  2080.   return (temp);
  2081. }
  2082.  
  2083. static void
  2084. memory_error_and_abort ()
  2085. {
  2086.   fprintf (stderr, "history: Out of virtual memory!\n");
  2087.   abort ();
  2088. }
  2089. #endif /* STATIC_MALLOC */
  2090.  
  2091. /* **************************************************************** */
  2092. /*                                    */
  2093. /*                Test Code                */
  2094. /*                                    */
  2095. /* **************************************************************** */
  2096. #ifdef TEST
  2097. main ()
  2098. {
  2099.   char line[1024], *t;
  2100.   int done = 0;
  2101.  
  2102.   line[0] = 0;
  2103.  
  2104.   while (!done)
  2105.     {
  2106.       fprintf (stdout, "history%% ");
  2107.       t = gets (line);
  2108.  
  2109.       if (!t)
  2110.     strcpy (line, "quit");
  2111.  
  2112.       if (line[0])
  2113.     {
  2114.       char *expansion;
  2115.       int result;
  2116.  
  2117.       using_history ();
  2118.  
  2119.       result = history_expand (line, &expansion);
  2120.       strcpy (line, expansion);
  2121.       free (expansion);
  2122.       if (result)
  2123.         fprintf (stderr, "%s\n", line);
  2124.  
  2125.       if (result < 0)
  2126.         continue;
  2127.  
  2128.       add_history (line);
  2129.     }
  2130.  
  2131.       if (strcmp (line, "quit") == 0) done = 1;
  2132.       if (strcmp (line, "save") == 0) write_history (0);
  2133.       if (strcmp (line, "read") == 0) read_history (0);
  2134.       if (strcmp (line, "list") == 0)
  2135.     {
  2136.       register HIST_ENTRY **the_list = history_list ();
  2137.       register int i;
  2138.  
  2139.       if (the_list)
  2140.         for (i = 0; the_list[i]; i++)
  2141.           fprintf (stdout, "%d: %s\n", i + history_base, the_list[i]->line);
  2142.     }
  2143.       if (strncmp (line, "delete", strlen ("delete")) == 0)
  2144.     {
  2145.       int which;
  2146.       if ((sscanf (line + strlen ("delete"), "%d", &which)) == 1)
  2147.         {
  2148.           HIST_ENTRY *entry = remove_history (which);
  2149.           if (!entry)
  2150.         fprintf (stderr, "No such entry %d\n", which);
  2151.           else
  2152.         {
  2153.           free (entry->line);
  2154.           free (entry);
  2155.         }
  2156.         }
  2157.       else
  2158.         {
  2159.           fprintf (stderr, "non-numeric arg given to `delete'\n");
  2160.         }
  2161.     }
  2162.     }
  2163. }
  2164.  
  2165. #endif /* TEST */
  2166.  
  2167. /*
  2168. * Local variables:
  2169. * compile-command: "gcc -g -DTEST -o history history.c"
  2170. * end:
  2171. */
  2172.